package com.wzy.netty.core.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * 描述
 * 创建人    Wzy
 * 创建时间: 2020-05-23  1:10
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol messageProtocol) throws Exception {
        int len = messageProtocol.getLen();
        byte[] content = messageProtocol.getContent();

        String msg = new String(content, CharsetUtil.UTF_8).trim();
        System.out.println("读取到客户端发送的消息: 长度=" + len + "内容=" + msg);

        System.out.println("服务器接收到消息数量=" + (++this.count));

        //服务端返回信息
        String response = "收到收到!";
        byte[] bytes = response.getBytes(CharsetUtil.UTF_8);
        int length = response.getBytes(CharsetUtil.UTF_8).length;
        MessageProtocol responseContent = new MessageProtocol();
        responseContent.setContent(bytes);
        responseContent.setLen(length);
        channelHandlerContext.writeAndFlush(responseContent);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }


}
